import 'package:flutter/foundation.dart';

///// 课程分类枚举
enum CourseCategory {
  all,         // 全部
  traditional, // 传统技艺
  folk,        // 民俗文化
  music,       // 音乐舞蹈
  craft,       // 手工艺品
  literature,  // 文学艺术
  philosophy,  // 哲学思想
}

// 课程类型枚举
enum CourseType {
  basic,       // 基础课程
  advanced,    // 进阶课程
  master,      // 大师课程
  workshop,    // 工作坊
  online,      // 在线课程
  offline,     // 线下课程
}

/// 课程状态枚举
enum CourseStatus {
  upcoming,    // 即将开课
  enrolling,   // 报名中
  ongoing,     // 进行中
  completed,   // 已结束
  cancelled,   // 已取消
}

/// 课程难度枚举
enum CourseDifficulty {
  beginner,    // 初级
  intermediate, // 中级
  advanced,    // 高级
  expert,      // 专家级
}

/// 讲师信息
class Instructor {
  final String id;
  final String name;
  final String avatar;
  final String title;        // 职称
  final String bio;          // 简介
  final List<String> expertise; // 专业领域
  final double rating;
  final int studentCount;    // 学生数量
  final int courseCount;     // 课程数量
  final List<String> achievements; // 成就
  final String contact;      // 联系方式

  const Instructor({
    required this.id,
    required this.name,
    this.avatar = '',
    this.title = '',
    this.bio = '',
    this.expertise = const [],
    this.rating = 0.0,
    this.studentCount = 0,
    this.courseCount = 0,
    this.achievements = const [],
    this.contact = '',
  });

  factory Instructor.fromJson(Map<String, dynamic> json) {
    return Instructor(
      id: json['id'] ?? '',
      name: json['name'] ?? '',
      avatar: json['avatar'] ?? '',
      title: json['title'] ?? '',
      bio: json['bio'] ?? '',
      expertise: List<String>.from(json['expertise'] ?? []),
      rating: (json['rating'] ?? 0.0).toDouble(),
      studentCount: json['student_count'] ?? 0,
      courseCount: json['course_count'] ?? 0,
      achievements: List<String>.from(json['achievements'] ?? []),
      contact: json['contact'] ?? '',
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'avatar': avatar,
      'title': title,
      'bio': bio,
      'expertise': expertise,
      'rating': rating,
      'student_count': studentCount,
      'course_count': courseCount,
      'achievements': achievements,
      'contact': contact,
    };
  }
}

/// 课程章节
class CourseChapter {
  final String id;
  final String title;
  final String description;
  final int duration;        // 时长（分钟）
  final String videoUrl;
  final List<String> materials; // 学习资料
  final bool isCompleted;
  final bool isLocked;
  final int order;

  const CourseChapter({
    required this.id,
    required this.title,
    this.description = '',
    this.duration = 0,
    this.videoUrl = '',
    this.materials = const [],
    this.isCompleted = false,
    this.isLocked = false,
    required this.order,
  });
  
  // Getter for lessons (for compatibility)
  List<dynamic> get lessons => []; // 返回空列表，实际应该根据业务需求实现

  factory CourseChapter.fromJson(Map<String, dynamic> json) {
    return CourseChapter(
      id: json['id'] ?? '',
      title: json['title'] ?? '',
      description: json['description'] ?? '',
      duration: json['duration'] ?? 0,
      videoUrl: json['video_url'] ?? '',
      materials: List<String>.from(json['materials'] ?? []),
      isCompleted: json['is_completed'] ?? false,
      isLocked: json['is_locked'] ?? false,
      order: json['order'] ?? 0,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      'description': description,
      'duration': duration,
      'video_url': videoUrl,
      'materials': materials,
      'is_completed': isCompleted,
      'is_locked': isLocked,
      'order': order,
    };
  }
}

/// 课程模型
class Course {
  final String id;
  final String title;
  final String description;
  final String coverImage;
  final CourseType type;
  final CourseStatus status;
  final CourseDifficulty difficulty;
  final Instructor instructor;
  final List<CourseChapter> chapters;
  final DateTime startDate;
  final DateTime endDate;
  final int duration;        // 总时长（分钟）
  final double price;
  final double originalPrice;
  final int maxStudents;     // 最大学生数
  final int currentStudents; // 当前学生数
  final String venue;        // 上课地点
  final String schedule;     // 上课时间安排
  final List<String> requirements; // 学习要求
  final List<String> outcomes;     // 学习成果
  final List<String> materials;    // 学习材料
  final DateTime createdAt;
  final DateTime updatedAt;
  final bool isFeatured;
  final double rating;
  final int reviewCount;
  final List<String> tags;
  final String category;     // 课程分类
  final String language;     // 授课语言
  final bool hasCertificate; // 是否有证书
  final Map<String, dynamic> metadata;

  const Course({
    required this.id,
    required this.title,
    required this.description,
    this.coverImage = '',
    required this.type,
    required this.status,
    required this.difficulty,
    required this.instructor,
    this.chapters = const [],
    required this.startDate,
    required this.endDate,
    this.duration = 0,
    this.price = 0.0,
    this.originalPrice = 0.0,
    this.maxStudents = 0,
    this.currentStudents = 0,
    this.venue = '',
    this.schedule = '',
    this.requirements = const [],
    this.outcomes = const [],
    this.materials = const [],
    required this.createdAt,
    required this.updatedAt,
    this.isFeatured = false,
    this.rating = 0.0,
    this.reviewCount = 0,
    this.tags = const [],
    this.category = '',
    this.language = '中文',
    this.hasCertificate = false,
    this.metadata = const {},
  });

  factory Course.fromJson(Map<String, dynamic> json) {
    return Course(
      id: json['id'] ?? '',
      title: json['title'] ?? '',
      description: json['description'] ?? '',
      coverImage: json['cover_image'] ?? '',
      type: CourseType.values.firstWhere(
        (e) => e.name == json['type'],
        orElse: () => CourseType.basic,
      ),
      status: CourseStatus.values.firstWhere(
        (e) => e.name == json['status'],
        orElse: () => CourseStatus.upcoming,
      ),
      difficulty: CourseDifficulty.values.firstWhere(
        (e) => e.name == json['difficulty'],
        orElse: () => CourseDifficulty.beginner,
      ),
      instructor: Instructor.fromJson(json['instructor'] ?? {}),
      chapters: (json['chapters'] as List<dynamic>? ?? [])
          .map((item) => CourseChapter.fromJson(item))
          .toList(),
      startDate: DateTime.parse(json['start_date'] ?? DateTime.now().toIso8601String()),
      endDate: DateTime.parse(json['end_date'] ?? DateTime.now().toIso8601String()),
      duration: json['duration'] ?? 0,
      price: (json['price'] ?? 0.0).toDouble(),
      originalPrice: (json['original_price'] ?? 0.0).toDouble(),
      maxStudents: json['max_students'] ?? 0,
      currentStudents: json['current_students'] ?? 0,
      venue: json['venue'] ?? '',
      schedule: json['schedule'] ?? '',
      requirements: List<String>.from(json['requirements'] ?? []),
      outcomes: List<String>.from(json['outcomes'] ?? []),
      materials: List<String>.from(json['materials'] ?? []),
      createdAt: DateTime.parse(json['created_at'] ?? DateTime.now().toIso8601String()),
      updatedAt: DateTime.parse(json['updated_at'] ?? DateTime.now().toIso8601String()),
      isFeatured: json['is_featured'] ?? false,
      rating: (json['rating'] ?? 0.0).toDouble(),
      reviewCount: json['review_count'] ?? 0,
      tags: List<String>.from(json['tags'] ?? []),
      category: json['category'] ?? '',
      language: json['language'] ?? '中文',
      hasCertificate: json['has_certificate'] ?? false,
      metadata: Map<String, dynamic>.from(json['metadata'] ?? {}),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      'description': description,
      'cover_image': coverImage,
      'type': type.name,
      'status': status.name,
      'difficulty': difficulty.name,
      'instructor': instructor.toJson(),
      'chapters': chapters.map((chapter) => chapter.toJson()).toList(),
      'start_date': startDate.toIso8601String(),
      'end_date': endDate.toIso8601String(),
      'duration': duration,
      'price': price,
      'original_price': originalPrice,
      'max_students': maxStudents,
      'current_students': currentStudents,
      'venue': venue,
      'schedule': schedule,
      'requirements': requirements,
      'outcomes': outcomes,
      'materials': materials,
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt.toIso8601String(),
      'is_featured': isFeatured,
      'rating': rating,
      'review_count': reviewCount,
      'tags': tags,
      'category': category,
      'language': language,
      'has_certificate': hasCertificate,
      'metadata': metadata,
    };
  }

  Course copyWith({
    String? id,
    String? title,
    String? description,
    String? coverImage,
    CourseType? type,
    CourseStatus? status,
    CourseDifficulty? difficulty,
    Instructor? instructor,
    List<CourseChapter>? chapters,
    DateTime? startDate,
    DateTime? endDate,
    int? duration,
    double? price,
    double? originalPrice,
    int? maxStudents,
    int? currentStudents,
    String? venue,
    String? schedule,
    List<String>? requirements,
    List<String>? outcomes,
    List<String>? materials,
    DateTime? createdAt,
    DateTime? updatedAt,
    bool? isFeatured,
    double? rating,
    int? reviewCount,
    List<String>? tags,
    String? category,
    String? language,
    bool? hasCertificate,
    Map<String, dynamic>? metadata,
  }) {
    return Course(
      id: id ?? this.id,
      title: title ?? this.title,
      description: description ?? this.description,
      coverImage: coverImage ?? this.coverImage,
      type: type ?? this.type,
      status: status ?? this.status,
      difficulty: difficulty ?? this.difficulty,
      instructor: instructor ?? this.instructor,
      chapters: chapters ?? this.chapters,
      startDate: startDate ?? this.startDate,
      endDate: endDate ?? this.endDate,
      duration: duration ?? this.duration,
      price: price ?? this.price,
      originalPrice: originalPrice ?? this.originalPrice,
      maxStudents: maxStudents ?? this.maxStudents,
      currentStudents: currentStudents ?? this.currentStudents,
      venue: venue ?? this.venue,
      schedule: schedule ?? this.schedule,
      requirements: requirements ?? this.requirements,
      outcomes: outcomes ?? this.outcomes,
      materials: materials ?? this.materials,
      createdAt: createdAt ?? this.createdAt,
      updatedAt: updatedAt ?? this.updatedAt,
      isFeatured: isFeatured ?? this.isFeatured,
      rating: rating ?? this.rating,
      reviewCount: reviewCount ?? this.reviewCount,
      tags: tags ?? this.tags,
      category: category ?? this.category,
      language: language ?? this.language,
      hasCertificate: hasCertificate ?? this.hasCertificate,
      metadata: metadata ?? this.metadata,
    );
  }

  /// 获取已报名学生数量
  int get enrolledCount => currentStudents;
  
  /// 检查用户是否已报名（这里简化处理，实际应该根据用户ID判断）
  bool get isEnrolled => false; // TODO: 实现真实的报名状态检查
  
  /// 检查用户是否已收藏
  bool get isFavorited => false; // TODO: 实现用户收藏状态检查

  /// 获取课程状态显示文本
  String get statusText {
    switch (status) {
      case CourseStatus.upcoming:
        return '即将开课';
      case CourseStatus.enrolling:
        return '报名中';
      case CourseStatus.ongoing:
        return '进行中';
      case CourseStatus.completed:
        return '已结束';
      case CourseStatus.cancelled:
        return '已取消';
    }
  }

  /// 获取课程类型显示文本
  String get typeText {
    switch (type) {
      case CourseType.basic:
        return '基础课程';
      case CourseType.advanced:
        return '进阶课程';
      case CourseType.master:
        return '大师课程';
      case CourseType.workshop:
        return '工作坊';
      case CourseType.online:
        return '在线课程';
      case CourseType.offline:
        return '线下课程';
    }
  }

  /// 获取难度显示文本
  String get difficultyText {
    switch (difficulty) {
      case CourseDifficulty.beginner:
        return '初级';
      case CourseDifficulty.intermediate:
        return '中级';
      case CourseDifficulty.advanced:
        return '高级';
      case CourseDifficulty.expert:
        return '专家级';
    }
  }

  /// 检查是否可以报名
  bool get canEnroll {
    return status == CourseStatus.upcoming && 
           currentStudents < maxStudents;
  }

  /// 获取剩余名额
  int get remainingSlots {
    return maxStudents - currentStudents;
  }

  /// 检查是否已满员
  bool get isFull {
    return currentStudents >= maxStudents;
  }

  /// 检查是否有折扣
  bool get hasDiscount {
    return originalPrice > price && originalPrice > 0;
  }

  /// 获取折扣百分比
  double get discountPercentage {
    if (!hasDiscount) return 0.0;
    return ((originalPrice - price) / originalPrice * 100);
  }

  /// 获取课程进度（已完成章节数/总章节数）
  double get progress {
    if (chapters.isEmpty) return 0.0;
    final completedChapters = chapters.where((c) => c.isCompleted).length;
    return completedChapters / chapters.length;
  }

  /// 获取总时长文本
  String get durationText {
    if (duration < 60) {
      return '${duration}分钟';
    } else {
      final hours = duration ~/ 60;
      final minutes = duration % 60;
      return minutes > 0 ? '${hours}小时${minutes}分钟' : '${hours}小时';
    }
  }

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is Course && other.id == id;
  }

  @override
  int get hashCode => id.hashCode;

  @override
  String toString() {
    return 'Course{id: $id, title: $title, status: $status, type: $type}';
  }
}

/// 课程筛选器
enum CourseFilter {
  all,         // 全部
  upcoming,    // 即将开课
  ongoing,     // 进行中
  completed,   // 已结束
  basic,       // 基础课程
  advanced,    // 进阶课程
  master,      // 大师课程
  workshop,    // 工作坊
  online,      // 在线课程
  offline,     // 线下课程
  featured,    // 精选
  free,        // 免费
  paid,        // 付费
}

/// 课程类型扩展
extension CourseTypeExtension on CourseType {
  String get displayName {
    switch (this) {
      case CourseType.basic:
        return '基础课程';
      case CourseType.advanced:
        return '进阶课程';
      case CourseType.master:
        return '大师课程';
      case CourseType.workshop:
        return '工作坊';
      case CourseType.online:
        return '在线课程';
      case CourseType.offline:
        return '线下课程';
    }
  }
}

/// 课程难度扩展
extension CourseDifficultyExtension on CourseDifficulty {
  String get displayName {
    switch (this) {
      case CourseDifficulty.beginner:
        return '初级';
      case CourseDifficulty.intermediate:
        return '中级';
      case CourseDifficulty.advanced:
        return '高级';
      case CourseDifficulty.expert:
        return '专家级';
    }
  }
}

/// 课程状态扩展
extension CourseStatusExtension on CourseStatus {
  String get displayName {
    switch (this) {
      case CourseStatus.upcoming:
        return '即将开课';
      case CourseStatus.enrolling:
        return '报名中';
      case CourseStatus.ongoing:
        return '进行中';
      case CourseStatus.completed:
        return '已结束';
      case CourseStatus.cancelled:
        return '已取消';
    }
  }
}

/// 课程筛选器扩展
extension CourseFilterExtension on CourseFilter {
  String get displayName {
    switch (this) {
      case CourseFilter.all:
        return '全部';
      case CourseFilter.upcoming:
        return '即将开课';
      case CourseFilter.ongoing:
        return '进行中';
      case CourseFilter.completed:
        return '已结束';
      case CourseFilter.basic:
        return '基础课程';
      case CourseFilter.advanced:
        return '进阶课程';
      case CourseFilter.master:
        return '大师课程';
      case CourseFilter.workshop:
        return '工作坊';
      case CourseFilter.online:
        return '在线课程';
      case CourseFilter.offline:
        return '线下课程';
      case CourseFilter.featured:
        return '精选';
      case CourseFilter.free:
        return '免费';
      case CourseFilter.paid:
        return '付费';
    }
  }
}